package wangZhong.app.dws;
/**
 * @author wangz
 * @date 2022/9/2 23:49
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import wangZhong.app.BaseAppV1;
import wangZhong.bean.TrafficOrderSynthesizeBean;
import wangZhong.common.Constant;
import wangZhong.util.DateFormatUtil;
import wangZhong.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsTradeOrderSynthesizeWindow extends BaseAppV1 {
    public static void main(String[] args) throws Exception {
       new DwsTradeOrderSynthesizeWindow().init(
               4010,
               2,
               "DwsTradeOrderSynthesize",
               Constant.TOPIC_DWD_TRADE_ORDER_DETAILS
       );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        SingleOutputStreamOperator<TrafficOrderSynthesizeBean> result = stream
            .map(JSON::parseObject)
            .map(new MapFunction<JSONObject, TrafficOrderSynthesizeBean>() {
                @Override
                public TrafficOrderSynthesizeBean map(JSONObject json) throws Exception {
                    return TrafficOrderSynthesizeBean.builder()
                        .orderAmountVc(json.getBigDecimal("final_amount"))
                        .userCt(1L)
                        .orderCt(1L)
                        .orderId(json.getString("order_id"))
                        .ts(json.getLong("ts") * 1000)
                        .build();

                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TrafficOrderSynthesizeBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getTs())
            )
            .keyBy(TrafficOrderSynthesizeBean::getOrderId)
            .window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
            .reduce(new ReduceFunction<TrafficOrderSynthesizeBean>() {
                        @Override
                        public TrafficOrderSynthesizeBean reduce(TrafficOrderSynthesizeBean bean1,
                                                                 TrafficOrderSynthesizeBean bean2) throws Exception {
                            bean1.setOrderCt(bean1.getOrderCt() + bean2.getOrderCt());
                            bean1.setUserCt(bean1.getUserCt() + bean2.getUserCt());

                            bean1.setOrderAmountVc(bean1.getOrderAmountVc().add(bean2.getOrderAmountVc()));

                            return bean1;

                        }
                    },
                new ProcessWindowFunction<TrafficOrderSynthesizeBean, TrafficOrderSynthesizeBean, String, TimeWindow>() {
                    @Override
                    public void process(String value,
                                        Context ctx,
                                        Iterable<TrafficOrderSynthesizeBean> element,
                                        Collector<TrafficOrderSynthesizeBean> out) throws Exception {
                        TrafficOrderSynthesizeBean bean = element.iterator().next();

                        bean.setStt(DateFormatUtil.toYmdHms(ctx.window().getStart()));
                        bean.setEdt(DateFormatUtil.toYmdHms(ctx.window().getEnd()));

                        bean.setCurDate(DateFormatUtil.toDate(System.currentTimeMillis()));

                        out.collect(bean);
                    }
                }
            );

        result.map(bean ->{
            SerializeConfig config = new SerializeConfig();
            config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
            String json = JSON.toJSONString(bean, config);
            System.out.println(json);
            return json;
        })
            .addSink(FlinkSinkUtil.getDorisSink("edu.dws_traffic_order_synthesize"));

    }
}
